package iamutkarshtiwari.github.io.ananas.editimage.fragment;

import iamutkarshtiwari.github.io.ananas.ResourceTable;
import iamutkarshtiwari.github.io.ananas.editimage.EditImageAbility;
import iamutkarshtiwari.github.io.ananas.editimage.ModuleConfig;
import iamutkarshtiwari.github.io.ananas.editimage.adapter.ColorPickerOwnAdapter;
import iamutkarshtiwari.github.io.ananas.editimage.bean.TextBean;
import iamutkarshtiwari.github.io.ananas.editimage.gesture.TransformInfo;
import iamutkarshtiwari.github.io.ananas.editimage.layout.ZoomLayout;
import iamutkarshtiwari.github.io.ananas.editimage.utils.*;
import iamutkarshtiwari.github.io.ananas.editimage.view.TextStickerView;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.Matrix;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.service.Window;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.image.PixelMap;
import ohos.multimodalinput.event.TouchEvent;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class AddTextFragment extends ComponentContainer {
    public static final int INDEX = ModuleConfig.INDEX_ADDTEXT;
    public static final String TAG = AddTextFragment.class.getName();

    private Component mainView;
    private TextStickerView textStickersParentView;
    private ZoomLayout zoomLayout;

    //    private InputMethodManager inputMethodManager;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();
    //    private List<Component> addedViews;
    private List<TextBean> textBeans;
    private TextBean textBean;


    private PageSlider mPageSlider;
    private EditImageAbility editImageAbility;

    private final Color mDefaultColor = new Color(Color.getIntColor("#ffF2F3F4"));
    private Color selectColor;

    private float mTextWidth = 0;
    private float mTextHigh = 0;
    private Component mAddTextComponent = null;
    private boolean move = false;

    public AddTextFragment(Context context, PageSlider pageSlider) {
        super(context);
        this.mPageSlider = pageSlider;
        this.editImageAbility = (EditImageAbility) context;
        initView();
    }

    public AddTextFragment(Context context, AttrSet attrSet) {
        super(context, attrSet);
        initView();
    }

    public AddTextFragment(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    /**
     * 初始化添加文字的主页面
     */
    private void initView() {
        mainView = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_fragment_add_text_layout, null, false);
        addComponent(mainView);

        textStickersParentView = editImageAbility.textStickerView;
//        textStickersParentView.updateImageBitmap(editImageAbility.getMainBit());
        textBeans = new ArrayList<>();

        zoomLayout = (ZoomLayout) editImageAbility.findComponentById(ResourceTable.Id_text_sticker_panel_frame);

        mainView.findComponentById(ResourceTable.Id_back_to_main).setClickedListener(component -> backToMain());

        mainView.findComponentById(ResourceTable.Id_add_text_btn).setClickedListener(component -> addTextDialog(null, null));

        move = false;
    }

    /**
     * 返回到主页面
     */
    public void backToMain() {
        clearAllStickers();
        editImageAbility.mode = EditImageAbility.MODE_NONE;
        mPageSlider.setCurrentPage(0, false);
        mPageSlider.setVisibility(Component.HIDE);
        textStickersParentView.setVisibility(Component.HIDE);
        zoomLayout.setVisibility(Component.HIDE);
        editImageAbility.setMainImageVisibility(Component.VISIBLE);
        editImageAbility.saveOrApply(false);
    }

    /**
     * 切换到addText界面，显示需要的控件
     */
    public void onShow() {
        editImageAbility.mode = EditImageAbility.MODE_TEXT;
        editImageAbility.textStickerView.setVisibility(VISIBLE);
        editImageAbility.textStickerView.updateImageBitmap(editImageAbility.getMainBit());
        zoomLayout.setVisibility(VISIBLE);
        editImageAbility.setMainImageVisibility(Component.HIDE);

        autoScaleImageToFitBounds();
    }

    /**
     * 图片自动适配控件的大小
     */
    private void autoScaleImageToFitBounds() {
        textStickersParentView.getComponentTreeObserver().addTreeLayoutChangedListener(new ComponentTreeObserver.GlobalLayoutListener() {
            @Override
            public void onGlobalLayoutUpdated() {
                textStickersParentView.getComponentTreeObserver().removeTreeLayoutChangedListener(this);
                scaleImage();
            }
        });
    }

    /**
     * 图片自动适配控件的大小
     */
    private void scaleImage() {
        final float mZoomLayoutWidth = zoomLayout.getWidth();
        final float mZoomLayoutHeight = zoomLayout.getHeight();

        final float imageViewWidth = textStickersParentView.getWidth();
        final float imageViewHeight = textStickersParentView.getHeight();

        // To avoid divideByZero exception
        if (imageViewHeight != 0 && imageViewWidth != 0 && mZoomLayoutHeight != 0 && mZoomLayoutWidth != 0) {
            final float offsetFactorX = mZoomLayoutWidth / imageViewWidth;
            final float offsetFactorY = mZoomLayoutHeight / imageViewHeight;

            float scaleFactor = Math.min(offsetFactorX, offsetFactorY);
            zoomLayout.setChildScale(scaleFactor);
        }
    }

    /**
     * 应用添加的文字到原图上，并且保存在主页面
     */
    public void applyTextImage() {
        // Hide borders of all stickers before save
        updateViewsBordersVisibilityExcept(null);
        compositeDisposable.clear();
        if (textBeans.isEmpty()) {
            backToMain();
            return;
        }
        Disposable applyTextDisposable = Observable.fromCallable(() -> getFinalBitmapFromView(textStickersParentView))
//                .subscribeOn(Schedulers.io())
//                .observeOn(Schedulers.mainThread())
                .subscribe(
                        bitmap -> {
                            if (textBeans.size() > 0) {
                                editImageAbility.changeMainBitmap(bitmap, true);
                            }
                            backToMain();
                        },
                        e -> {
                            e.printStackTrace();
                            backToMain();
                            MyToast.show(getContext(), ResourceTable.String_iamutkarshtiwari_github_io_ananas_save_error);
                        });
        compositeDisposable.add(applyTextDisposable);
        textBeans.clear();
    }

    private void clearAllStickers() {
        editImageAbility.getUITaskDispatcher().asyncDispatch(() -> {
            textStickersParentView.removeAllComponents();//removeAllViews
        });
    }

    /**
     * 隐藏边框以及移除按钮
     *
     * @param keepView 对应需要修改的view
     */
    private void updateViewsBordersVisibilityExcept(Component keepView) {
        for (TextBean view : textBeans) {
            if (view.getView() != keepView) {
                StackLayout border = (StackLayout) view.getView().findComponentById(ResourceTable.Id_sticker_border);
                border.setBackground(null);
                Image closeBtn = (Image) view.getView().findComponentById(ResourceTable.Id_sticker_delete_btn);
                LogUtils.loge("gongmengfei", "updateView" + closeBtn.getComponentPosition().getCenterX() + " " + closeBtn.getComponentPosition().getCenterY());
                closeBtn.setVisibility(Component.HIDE);
            }
        }
    }

    /**
     * 显示边框
     *
     * @param keepView 对应需要修改的view
     */
    private void updateViewsBordersVisibilityShow(Component keepView) {
        StackLayout border = (StackLayout) keepView.findComponentById(ResourceTable.Id_sticker_border);
        int imageRes = ResourceTable.Graphic_background_border;
        border.setBackground(new ShapeElement(getContext(), imageRes));
        Image closeBtn = (Image) keepView.findComponentById(ResourceTable.Id_sticker_delete_btn);
        closeBtn.setVisibility(Component.VISIBLE);
        mAddTextComponent = keepView;
        textBean = getTextBean(keepView.getTag());
    }

    private TextBean getTextBean(Object tag) {
        for (TextBean bean : textBeans) {
            if (bean.getView().getTag() == tag) {
                return bean;
            }
        }
        return null;
    }


    private PixelMap getFinalBitmapFromView(Component view) {
        if (null != textStickersParentView) {
            PixelMap pixelMap = textStickersParentView.getBitmapHolderImageView().getPixelMap();
//            float widthImage = pixelMap.getImageInfo().size.width;
//            float heightImage = pixelMap.getImageInfo().size.height;
//            float scaleX = widthImage / view.getWidth();//.screenWidth();  //1200  2.5625
//            float scaleY = heightImage / view.getHeight();//PxUtil.screenHeight();  //2499  1.63905
//            float width = textStickersParentView.getBitmapHolderImageView().getComponentPosition().getCenterX();
//            float height = textStickersParentView.getBitmapHolderImageView().getComponentPosition().getCenterY();
//            float startPositionY = heightImage / 2 + PxUtil.vp2px(4) * scaleY + mTextHigh / 2 * scaleY;
//            float certen = startPositionY + mMoveDy * scaleX;
        }

        Matrix touchMatrix = editImageAbility.getImageViewMatrix();
        float[] data = touchMatrix.getData();
        Matrix3 cal = new Matrix3(data);
        Matrix3 inverseMatrix = cal.inverseMatrix();
        Matrix matrix = new Matrix(inverseMatrix.getValues());

        float[] matrixDa = matrix.getData();//getValues(f);
//        float dx = matrixDa[2];            //Matrix.MTRANS_X
//        float dy = matrixDa[5];            //Matrix.MTRANS_Y
        float scale_x = matrixDa[0];       //Matrix.MSCALE_X
        float scale_y = matrixDa[4];       //Matrix.MSCALE_Y

        PixelMap pixelMap = textStickersParentView.getBitmapHolderImageView().getPixelMap();
        for (TextBean bean : textBeans) {
            textStickersParentView.drawText(pixelMap, bean.getShowResult(), bean.getMoveDx(),
                    bean.getMoveDy(), bean.getShowColor(), bean.getTextSize(), scale_x, scale_y, bean.getText(), scale, scaleType);
            pixelMap = textStickersParentView.getPixelMap();
        }
//        textStickersParentView.drawTextList(textStickersParentView.getBitmapHolderImageView().getPixelMap(), textBeans, scale_x, scale_y, scale, scaleType);  //   600 1000 多 650 1150  // 50 350
        return textStickersParentView.getPixelMap();
    }

    /**
     * 输入文字后，添加文字的预览效果，还可以进行文字的移动和设置相关操作
     *
     * @param text 添加的文字
     * @param colorCodeTextView 字体的颜色
     */
    float lastx = 0;
    float lasty = 0;
    public int textShowMaxWidth = 0;//单行最大宽度
    public int textShowMaxHeight = 0;
    int scaleType = 1;//1 x的缩放比  2 Y的缩放比
    float scale = 0;
    int mode = 0;// 0 单指移动 1 双指缩放和旋转
    float spacing;
    float degree;
    float rotation;
    float downCenterX = 0;
    float downCenterY = 0;
    int showWidth;
    int showHeight;

    private void addText(String text, final Color colorCodeTextView, int textSize) {
        float widthImage = editImageAbility.getMainBit().getImageInfo().size.width;
        float heightImage = editImageAbility.getMainBit().getImageInfo().size.height;

        float scaleX = widthImage / textStickersParentView.getWidth();//.screenWidth();  //1200  2.5625
        float scaleY = heightImage / textStickersParentView.getHeight();

        scale = Math.min(scaleX, scaleY);
        if (scaleX < scaleY) {
            scaleType = 1;
        } else {
            scaleType = 2;
        }
        if (scaleType == 2) {
            showWidth = textStickersParentView.getWidth();
            showHeight = (int) (heightImage * (showWidth / widthImage));
        } else {
            showHeight = textStickersParentView.getHeight();
            showWidth = (int) (widthImage * (showHeight / heightImage));
        }
        Component textStickerView = getTextStickerLayout();

        Text textInputTv = (Text) textStickerView.findComponentById(ResourceTable.Id_text_sticker_tv);
//        final StackLayout frameBorder = (StackLayout) textStickerView.findComponentById(ResourceTable.Id_sticker_border);
        textInputTv.setText(text);
        textInputTv.setTextColor(colorCodeTextView);//显示的文字
        textInputTv.setMaxTextHeight(BigDecimal.valueOf(editImageAbility.getBitmapRect().bottom).subtract(BigDecimal.valueOf(editImageAbility.getBitmapRect().top)).intValue());
        textShowMaxWidth = BigDecimal.valueOf(editImageAbility.getBitmapRect().right).subtract(BigDecimal.valueOf(editImageAbility.getBitmapRect().left)).intValue();
        textInputTv.setMaxTextWidth(textShowMaxWidth);
        textInputTv.setBindStateChangedListener(getBindStateChangedListener(textInputTv));
        textStickerView.setTag(componentTag++);//获取的ID都为-1 用tag 做标识符
        textStickerView.setTouchEventListener(getMyTouchEventListener());
        addViewToParent(textStickerView);
        mAddTextComponent = textStickerView;

        textBean = new TextBean();
        textBean.setView(textStickerView);
        textBean.setText(textInputTv);
        textBean.setShowResult(text);
        textBean.setShowColor(colorCodeTextView);
        textBean.setTextSize(textSize);
        textBeans.add(textBean);


        textStickerView.setClickedListener(component -> {
            if (mAddTextComponent.getTag() == component.getTag()) {
                addTextDialog(textInputTv.getText(), component);
//                addTextDialog(textInputTv.getText(), textStickerView);
            } else {
                updateViewsBordersVisibilityExcept(null);
                updateViewsBordersVisibilityShow(component);
            }
        });
    }

    //自增tag
    int componentTag = 1;

    private TouchEventListener getMyTouchEventListener() {
        return (component, touchEvent) -> {
            //如果触摸的不是当前选中的 就不做移动操作
            if (component.getTag() != mAddTextComponent.getTag()) {
                return false;
            }
            boolean ret = true;
//            float oneFingerx = 0;
//            float oneFingery = 0;
//            float twoFingerx = 0;
//            float twoFingery = 0;
            float otherx = 0;
            float othery = 0;
            float current = 0;
            float positionX = touchEvent.getPointerScreenPosition(0).getX();// - location[0];
            float positionY = touchEvent.getPointerScreenPosition(0).getY();// - location[1];
            if (touchEvent.getPointerCount() > 1) {
                otherx = touchEvent.getPointerScreenPosition(1).getX();// - location[0];
                othery = touchEvent.getPointerScreenPosition(1).getY();
            }
            switch (touchEvent.getAction()) {
                case TouchEvent.PRIMARY_POINT_DOWN:
                    LogUtil.loge("gongmengfei" + "PRIMARY_POINT_DOWN" + positionX + " " + positionY);
                    lastx = positionX;
                    lasty = positionY;
                    ret = true;
                    break;
                case TouchEvent.POINT_MOVE:
                    LogUtil.loge("gongmengfei" + "POINT_MOVE" + positionX + " " + positionY);
//                        if(mode == 0) {
                    onActionMove(positionX - lastx, positionY - lasty);  //需要重新设置
                    lastx = positionX;
                    lasty = positionY;
                    /*}else if(mode == 1) {
                        if(touchEvent.getPointerCount() >1) {
                            setTransforminof(textStickerView, touchEvent);
                        }
                    }*/
                    ret = true;
                    break;
                case TouchEvent.OTHER_POINT_DOWN:  //多只触摸
                    if (touchEvent.getPointerCount() > 1) {
//                            mode = 1;
                    }
                    spacing = getSpacing(touchEvent);
                    degree = getDegree(touchEvent);
//                    oneFingerx = x;
//                    oneFingery = y;
//                    twoFingerx = otherx;
//                    twoFingery = othery;
                    downCenterX = (otherx + positionX) / 2;
                    downCenterY = (othery + positionY) / 2;
                    predeltaX = downCenterX;
                    predeltaY = downCenterY;
                    prevFingerDiffX = otherx - positionX;
                    prevFingerDiffY = othery - positionY;
//                    prevSpanVector = new Vector2D(prevFingerDiffX, prevFingerDiffY);
                    previousSpan = getPreviousSpan();
                    ret = false;
                    break;
                case TouchEvent.OTHER_POINT_UP: //多只离开
                    ret = false;
                    break;
                case TouchEvent.CANCEL:
                case TouchEvent.PRIMARY_POINT_UP:
                    if (positionY < 200 || positionY > PxUtil.screenHeight() - 60) {
                        LogUtils.loge("Monkey 666 PRIMARY_POINT_UP2");
                        mAddTextComponent.setTranslation(0, 0);
                    }
                    mode = 0;
                    ret = false;
                    break;
            }
            return ret;
        };
    }

    private BindStateChangedListener getBindStateChangedListener(Text textField) {
        return new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                mTextWidth = textField.getWidth();
                mTextHigh = textField.getHeight();
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {

            }
        };
    }


    //    Vector2D prevSpanVector;
//    Vector2D currSpanVector;
    float predeltaX = 0;
    float predeltaY = 0;
    //    float minimumScale = 0.4f;
//    float maximumScale = 10.0f;
//    float currentSpan = 0;
    float previousSpan = 0;
//
//    private void setTransforminof(Component view, TouchEvent touchEvent) {
//        final int currIndex0 = touchEvent.getPointerId(0);//当前两个手指
//        final int currIndex1 = touchEvent.getPointerId(1);
//        float cx1 = 0;
//        float cy1 = 0;
//
//        final float cx0 = touchEvent.getPointerScreenPosition(currIndex0).getX();
//        final float cy0 = touchEvent.getPointerScreenPosition(currIndex0).getY();
//        if (touchEvent.getPointerCount() > 1) {
//            cx1 = touchEvent.getPointerScreenPosition(currIndex1).getX();
//            cy1 = touchEvent.getPointerScreenPosition(currIndex1).getY();
//        }
//
//        final float cvx = BigDecimal.valueOf(cx1).subtract(BigDecimal.valueOf(cx0)).floatValue();
//        final float cvy = BigDecimal.valueOf(cy1).subtract(BigDecimal.valueOf(cy0)).floatValue();
//        currFingerDiffX = cvx;
//        currFingerDiffY = cvy;
//
//        currSpanVector = new Vector2D(cvx, cvy);
//        currentSpan = getCurrentSpan();
//
//
//        TransformInfo info = new TransformInfo();
//        info.deltaScale = (currentSpan / previousSpan);//multiTouchListener.isScaleEnabled ? detector.getScaleFactor() : 1.0f;;
//        info.deltaAngle = VectorAngle.getAngle(prevSpanVector, currSpanVector);
//        info.deltaX = (cx0 + cx1) / 2 - predeltaX;
//        info.deltaY = (cy0 + cy1) / 2 - predeltaY;
//        info.minimumScale = minimumScale;
//        info.maximumScale = maximumScale;
//
//        move(view, info);
//        predeltaX = (cx0 + cx1) / 2;
//        predeltaY = (cy0 + cy1) / 2;
//        prevSpanVector = currSpanVector;
//        previousSpan = currentSpan;
//    }

    float currFingerDiffX = 0;
    float currFingerDiffY = 0;

    private float getCurrentSpan() {
        final double cvx = currFingerDiffX;
        final double cvy = currFingerDiffY;
        return (float) Math.sqrt(cvx * cvx + cvy * cvy);
    }

    float prevFingerDiffX = 0;
    float prevFingerDiffY = 0;

    private float getPreviousSpan() {
        final double pvx = prevFingerDiffX;
        final double pvy = prevFingerDiffY;
        return (float) Math.sqrt(pvx * pvx + pvy * pvy);
    }


    private void move(Component view, TransformInfo info) {
        adjustTranslation(view, info.deltaX, info.deltaY);  // 移动

        float scale = view.getScaleX() * info.deltaScale;
//        LogUtil.loge("gongmengfei"+"scale="+info.deltaScale+" "+scale);

        scale = Math.max(info.minimumScale, Math.min(info.maximumScale, scale));
        if (scale != 10) {
            view.setScaleX(scale);   //放大
            view.setScaleY(scale);   //放大
        }
        float rotation = adjustAngle(BigDecimal.valueOf(view.getRotation()).add(BigDecimal.valueOf(info.deltaAngle)).floatValue());
//        LogUtil.loge("gongmengfei"+"rotate ="+rotation);
        view.setRotation(rotation);
    }

    private void adjustTranslation(Component view, float deltaX, float deltaY) {
        view.setTranslation(BigDecimal.valueOf(view.getTranslationX()).add(BigDecimal.valueOf(deltaX)).floatValue(),
                BigDecimal.valueOf(view.getTranslationY()).add(BigDecimal.valueOf(deltaY)).floatValue());
    }


    private float adjustAngle(float degrees) {
        BigDecimal bigDecimal = BigDecimal.valueOf(360);
        if (degrees > 180.0f) {
            degrees = BigDecimal.valueOf(degrees).subtract(bigDecimal).floatValue();
//            degrees -= 360.0f;
        } else if (degrees < -180.0f) {
//            degrees += 360.0f;
            degrees = BigDecimal.valueOf(degrees).add(bigDecimal).floatValue();
        }
        return degrees;
    }

    // 触碰两点间距离
    private float getSpacing(TouchEvent event) {
        //通过三角函数得到两点间的距离
        double x = (double) event.getPointerScreenPosition(0).getX() - (double) event.getPointerScreenPosition(1).getX();
        double y = (double) event.getPointerScreenPosition(0).getY() - (double) event.getPointerScreenPosition(1).getY();
        return (float) Math.sqrt(x * x + y * y);
    }

    // 取旋转角度
    private float getDegree(TouchEvent event) {
        //得到两个手指间的旋转角度
        double delta_x = (double) event.getPointerScreenPosition(0).getX() - (double) event.getPointerScreenPosition(1).getX();
        double delta_y = (double) event.getPointerScreenPosition(0).getY() - (double) event.getPointerScreenPosition(1).getY();
        double radians = Math.atan2(delta_y, delta_x);
        return (float) Math.toDegrees(radians);
    }

//    private float calAngle(Point point1, Point point2, Point point3, Point point4) {
//        float angle = 0;
//        float lineAngel = getAngleOfLineBetweenTwoPoints(point1.getPointX(), point1.getPointY(), point2.getPointX(), point2.getPointY());
//        float lineAnge2 = getAngleOfLineBetweenTwoPoints(point3.getPointX(), point3.getPointY(), point4.getPointX(), point4.getPointY());
////        float firsty = Math.abs(point1.getPointY() - point3.getPointY());
////        float secondy = Math.abs(point2.getPointY() - point4.getPointY());
//    /*    if(firsty > secondy) {
//            //第一个点在转
//            if (point3.getPointY() > point1.getPointY()) { //下转
//                angle  = lineAnge2 - lineAngel;
//            } else {  //上转
//
//            }
//        }else{
//            //第二个点在转
//        }*/
//        angle = lineAngel - lineAnge2;
//        return angle;
//    }

    //两个点的角度
    public static float getAngleOfLineBetweenTwoPoints(float x1, float x2, float y1, float y2) {
        double xDiff = (double) x2 - (double) x1;
        double yDiff = (double) y2 - (double) y1;
        return (float) (Math.atan2(yDiff, xDiff) * (180D / Math.PI));
    }

    private void addViewToParent(Component view) {
        DependentLayout.LayoutConfig params = new DependentLayout.LayoutConfig(
                LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT);
        params.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT, DependentLayout.LayoutConfig.TRUE);

//        textStickersParentView.removeAllComponents();
//        textStickersParentView.updateImageBitmap(editImageAbility.getMainBit());
//        editImageAbility.getUITaskDispatcher().asyncDispatch(new Runnable() {
//            @Override
//            public void run() {
        textStickersParentView.addComponent(view, params);
//            }
//        });
        //mTextPositionX  设置显示的地方
        updateViewsBordersVisibilityExcept(view);
    }


    private Component getTextStickerLayout() {
        Component rootView = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_view_text_sticker_item, null, false);
        Text addText = (Text) rootView.findComponentById(ResourceTable.Id_text_sticker_tv);
        if (addText != null) {
            addText.setTextAlignment(TextAlignment.CENTER);
            Image imgClose = (Image) rootView.findComponentById(ResourceTable.Id_sticker_delete_btn);
            if (imgClose != null) {
                imgClose.setClickedListener(component -> deleteViewFromParent(rootView));
            }
        }
        return rootView;
    }

    private void deleteViewFromParent(Component view) {
        textStickersParentView.removeComponent(view);
        TextBean textBean = getTextBean(view.getTag());
        if (textBean != null) {
            textBeans.remove(textBean);
        }
        textStickersParentView.invalidate();
//        updateViewsBordersVisibilityExcept(null);
    }

    /**
     * 添加文字的dialog，进行文字输入和颜色选择
     *
     * @param ownString    添加的文字
     * @param addComponent 对应添加的view
     */
    private void addTextDialog(String ownString, Component addComponent) {
        TextBean textBean = null;
        if (addComponent != null) {
            textBean = getTextBean(addComponent.getTag());
        }
        CommonDialog commonDialog = new CommonDialog(mContext);
        Window window = commonDialog.getWindow();
        int width = LayoutConfig.MATCH_PARENT;
        int height = LayoutConfig.MATCH_PARENT;
        window.setWindowLayout(width, height);

        Component component1 = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_dialog_edit_text_sticker, null, false);
        commonDialog.getWindow().setBackgroundColor(new RgbColor((Color.TRANSPARENT).getValue()));
        commonDialog.setContentCustomComponent(component1);

        TextField textField = (TextField) component1.findComponentById(ResourceTable.Id_add_text_edit_text);
        selectColor = mDefaultColor;
        if (textBean != null) {
            selectColor = textBean.getShowColor();
        }
        textField.setTextColor(selectColor);

        setTextIndexColor(textField, "#013630");
        if (ownString != null) {
            textField.setText(ownString);
        }
        Text mDone = (Text) component1.findComponentById(ResourceTable.Id_add_text_done_tv);
        ListContainer listContainer = (ListContainer) component1.findComponentById(ResourceTable.Id_add_text_color_picker_recycler_view);
        ColorPickerOwnAdapter mColorPickerAdapter = new ColorPickerOwnAdapter(mContext);
        listContainer.setOrientation(Component.HORIZONTAL);
        listContainer.setItemProvider(mColorPickerAdapter);

        listContainer.setItemClickedListener((listContainer1, component, i, l) -> {
            textField.setTextColor(new Color(mColorPickerAdapter.getColor(i)));
            selectColor = new Color(mColorPickerAdapter.getColor(i));
        });
        commonDialog.show();

        new EventHandler(EventRunner.getMainEventRunner())
                .postTask(() -> {
                    textField.requestFocus();
                    textField.simulateClick();
                }, 300);
        TextBean finalTextBean = textBean;
        final boolean[] doneClick = {true};
        mDone.setClickedListener(component -> {
            if (!doneClick[0]) {
                return;
            }
            doneClick[0] = false;
            String showResult = textField.getText().trim();
            move = false;
            if (showResult != null && showResult.length() != 0) {
                //没有输入内容
                textStickersParentView.setVisibility(VISIBLE);
            }
            if (ownString == null || addComponent == null) {
                if (showResult != null && showResult.length() != 0) {
                    addText(showResult, selectColor, textField.getTextSize());
                }
                commonDialog.remove();
            } else {

                Text text = (Text) addComponent.findComponentById(ResourceTable.Id_text_sticker_tv);

                text.setText(showResult);
                ((Text) addComponent.findComponentById(ResourceTable.Id_text_sticker_tv)).setTextColor(selectColor);
                if (finalTextBean != null) {
                    finalTextBean.setShowResult(showResult);
                    finalTextBean.setShowColor(selectColor);
                }

                new EventHandler(EventRunner.getMainEventRunner()).postTask(() -> {
//                    addComponent.setFocusable(FOCUS_ENABLE);
//                    addComponent.setTouchFocusable(true);
//                    addComponent.requestFocus();
                    //在一个父容器是DependentLayout，动态添加Text去通过TouchEventListener监听，
                    // 设置Text 的 setTranslation跟随移动。现在动态修改Text的文本，会Text改变宽度，
                    // 位置会刷新到初始点，Translation不生效。。  延迟设置2次，位置就会刷新，等待验证
                    mAddTextComponent.setTranslation(finalTextBean.getMoveDx() - 1, finalTextBean.getMoveDy() - 1);
                    mAddTextComponent.setTranslation(finalTextBean.getMoveDx() + 1, finalTextBean.getMoveDy() + 1);
                    mAddTextComponent.setTranslation(finalTextBean.getMoveDx(), finalTextBean.getMoveDy());
                    commonDialog.remove();
                }, 15);
            }

        });
    }


    //设置光标颜色
    private void setTextIndexColor(TextField textField, String color) {
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setShape(ShapeElement.LINE); // 设置背景类型
//    RgbColor rgbColor = RgbColor.fromArgbInt(Color.getIntColor("#009688"));
        RgbColor rgbColor = RgbColor.fromArgbInt(Color.getIntColor(color));
        shapeElement.setRgbColors(new RgbColor[]{rgbColor, rgbColor}); // 设置颜色值 起始与结束时的颜色
        shapeElement.setStroke(AttrHelper.vp2px(44, getContext()), rgbColor); // 设置光标高度
        textField.setCursorElement(shapeElement); // 设置光标背景色
    }


    /**
     * * 移动操作，将添加文字的布局移动到指定位置
     *
     * @param dx X轴移动距离
     * @param dy Y轴移动距离
     */
    private void onActionMove(float dx, float dy) {
        float mMoveDx = (float) ((double) mAddTextComponent.getTranslationX() + (double) dx);
        float mMoveDy = (float) ((double) mAddTextComponent.getTranslationY() + (double) dy);
        if (textBean != null) {
            textBean.setMoveDx(mMoveDx);
            textBean.setMoveDy(mMoveDy);
        }
        mAddTextComponent.setTranslation(mMoveDx, mMoveDy); //位置不变

//        mAddTextComponent.setBindStateChangedListener(new BindStateChangedListener() {
//            @Override
//            public void onComponentBoundToWindow(Component component) {
//            }
//
//            @Override
//            public void onComponentUnboundFromWindow(Component component) {
//
//            }
//        });
        move = true;
    }


}
